package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/url"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// todo: add your logic here and delete this line
	url_ := "https://api.nutpi.net/login"
	// 创建一个请求
	// 构建表单数据
	formData := url.Values{}
	formData.Add("type", req.Type)
	formData.Add("mobile", req.Mobile)
	formData.Add("password", req.Password)
	formData.Add("captcha", req.Captcha)
	r, err := http.NewRequest("POST", url_, bytes.NewBufferString(formData.Encode()))
	if err != nil {
		l.Error(err)
		return nil, err
	}

	// 设置请求头
	r.Header.Set("x-requested-with", "XMLHttpRequest")
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
	//ctx := context.Background()
	//res, err_ := httpc.Do(ctx, http.MethodGet, url, nil)
	res, err_ := httpc.DoRequest(r)
	if err_ != nil {
		l.Error(err_)
		return nil, err
	}

	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}
	//格式化输出json
	var str bytes.Buffer
	_ = json.Indent(&str, []byte(body), "", "    ")
	l.Debugf("formated: ", str.String())
	//l.Debug(keyValue)
	var result types.Result

	result.Success = gjson.GetBytes(body, "success").String()
	if result.Success != "true" {
		errorMessage := gjson.GetBytes(body, "error").String()
		l.Errorf("Login failed: %s", errorMessage)
		resp = &types.LoginResp{
			Code:    1001,
			Message: errorMessage,
			Data:    result,
		}
		return resp, nil
	}

	systemUser := gjson.GetBytes(body, "systemUser")

	result.SysUser.UserId = systemUser.Get("userId").String()
	result.SysUser.UserName = systemUser.Get("userName").String()
	result.SysUser.Account = systemUser.Get("account").String()
	result.SysUser.Nickname = systemUser.Get("nickname").String()
	result.SysUser.AvatarPath = systemUser.Get("avatarPath").String()
	result.SysUser.AvatarName = systemUser.Get("avatarName").String()
	result.SysUser.SecurityDigest = systemUser.Get("securityDigest").String()
	result.SysUser.RememberMe = systemUser.Get("rememberMe").Bool()
	result.SysUser.OpenId = systemUser.Get("openId").String()

	// 解析 accessToken 和 refreshToken 字段
	result.AccessToken = gjson.GetBytes(body, "accessToken").String()
	result.RefreshToken = gjson.GetBytes(body, "refreshToken").String()
	//t := reflect.TypeOf(keyVal["count"])
	//l.Debugf("Type: %v\n", t)
	resp = &types.LoginResp{
		Code:    0,
		Message: res.Status,
		Data:    result,
	}
	return resp, nil
}
